/**
 * 2006-9-4 15:26:15
 * SetCharacterEncodingFilter.java
 */
package org.lilystudio.veryftp.common;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * @author Samson
 * 
 */
public class SetCharacterEncodingFilter implements Filter {

	private Log log = LogFactory.getLog(SetCharacterEncodingFilter.class);

	protected FilterConfig filterConfig;

	protected String encoding;

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
	 */
	public void init(FilterConfig filterConfig) throws ServletException {
		this.filterConfig = filterConfig;
		this.encoding = filterConfig.getInitParameter("encoding");
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest,
	 *      javax.servlet.ServletResponse, javax.servlet.FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain filterChain) throws IOException, ServletException {
		if (this.encoding != null) {
			request.setCharacterEncoding(this.encoding);
			log.info("Set request character encoding to " + this.encoding);
		} else {
			log.warn("Haven't set request character encoding in "
					+ this.getClass().getName() + ". Default encoding: "
					+ request.getCharacterEncoding());
		}
		filterChain.doFilter(request, response);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.servlet.Filter#destroy()
	 */
	public void destroy() {
		this.encoding = null;
		this.filterConfig = null;
	}

}
